<?php
	///////////////////////
	// GLOBAL PARAMETERS //
	///////////////////////
	
	$intSpaceBetweenWorkAndHomeEmailX = 150;
	$intSpaceBetweenWorkAndMobNumX = 85;
	$intLineSepBetFmlySize = 20;
	$intSmallLineSepSize = 20;
	$intLineSepSize = 26;
	$intFirstNameIndentX = 165;
	$intMinLeftPositionX = 50;
	$HomeAddrHeightY = 90;

	$intLeftDetailsIndentX = 40;
	$intFirstDetailsX = 168;

	$intLeftEmailDetailsIndentX = $intFirstDetailsX + 150;
	$intLeftEmailDetailsIndentX = 300;

	$intIndvRoleIndentX = 300;
	$intHomeTelephoneIndentX = 360;
	$intLeftDetailsX = 80;
	$intMinSepAfterAddrY = 1;    // spacing between families
	$intPageCountPosY = 8;
	$intImageWidth = 110;

	//////////////////////////
	// INITIALISE VARIABLES //
	//////////////////////////
	$maxFamilySize = 0;
	$bottom_image_Y = 0;
	$intTopOfAddressY = 0;
	$CSVOutput = "";
	$CSVOutput_Indv = "";
	$CSVOutput_Fmly = "";
	$bCSV_FirstRow = TRUE;
	$CSV_FirstRow = "";


	$XMLOutput = "";
	$XMLOutput_Indv = "";
	$XMLOutput_Fmly = "";
	$XMLIndent = "     ";
	$XMLOutput_IndvFamily = "";
	///////////////////////
	//   font            //
	///////////////////////
	$NormalFont = "Helvetica";
	$BoldFont = "Helvetica-Bold";
	$tinyFontSize = 14; // orig 8     // Role
	$smallFontSize = 16; // orig 10  // address
	$mediumFontSize = 20; // orig 12 // first Name
	$largeFontSize = 24; // orig 16  // Surname and Home PhoneNumber
	$hugeFontSize = 40; // orig 40

	///////////////////////
	//   PAGE SIZE (A4)  //
	///////////////////////
	$intPageSizeX = 595;  // ISO Standard A4 width
	$intPageSizeY = 842;  // ISO Standard A4 length
	$intTopOfPageY = 800; // maximum top of page to use
	$intTopOfPageX = 45;  // minimum left of page to use
	$intMinBottomPageY = 0;  // minimum bottom of page to use  42

	///////////////////////
	// LINE CONSTRAINTS  //
	///////////////////////
	$intLineSpaceToLeaveAtBothEnds = 40;
	$intLineSepLeftX = $intLineSpaceToLeaveAtBothEnds;
	$intLineSepRightX = $intPageSizeX - $intLineSpaceToLeaveAtBothEnds-10; // 595 is A4 page width

	///////////////////////////
	// DEFAULT ITEMS TO SHOW //
	///////////////////////////
	$bShowPrivateResidentialAddressesAsXXX = TRUE;  // done
	$bShowPrivateTelephoneNumbersAsXXX = TRUE;      // done
	$bShowPrivateEmailAddressesAsXXX = TRUE;		//done
	$bShowFamilyPicture = FALSE;
	$bShowRole = FALSE;
	$bShowGender = FALSE;
	$bShowWorkPhoneNumber = FALSE;
	$bShowWorkEmailAddress = FALSE;
	$bShowHomeEmailAddress = FALSE;
	$bShowMobilePhoneNumber = FALSE;
    $bShowSchoolGrade = FALSE;
	$bShowTitlePage = FALSE;
	$bShowPageNumber = FALSE;
	$bHidePrivateData = TRUE;
	$bCSVOutput = FALSE;
	$bXMLOutput = FALSE;
	//////////////////////////////////////////////////////
	// GPAC Database is Copyright 2003 Colin Todd       //
	// Written by Colin Todd - All rights reserved.     //
	//                                                  //
	// colintodd@myfastmail.com                         //
	//////////////////////////////////////////////////////

	$root = '../';
	include($root.'include/dbconnect.php');
//	check user is logged in
//	include_once('_includes/master_include.php');

	include($root .'include/config.php');
	include($root.'include/functions.php');

	$bShowPrivateResidentialAddressesAsXXX = @$_GET['ShowPrivateRA'];
	$bShowPrivateTelephoneNumbersAsXXX = @$_GET['ShowPrivatePN'];
	$bShowPrivateEmailAddressesAsXXX = @$_GET['ShowPrivateEA'];
	$bShowFamilyPicture = @$_GET['ShowFmlyPic'];
	$bShowRole = @$_GET['ShowRole'];
	$bShowGender = @$_GET['ShowGender'];
	$bShowWorkPhoneNumber = @$_GET['ShowWrkPN'];
	$bShowWorkEmailAddress = @$_GET['ShowWrkEA'];
	$bShowHomeEmailAddress = @$_GET['ShowHomeEA'];
	$bShowMobilePhoneNumber = @$_GET['ShowMob'];
    $bShowSchoolGrade = @$_GET['ShowSchoolGde'];
	$bShowTitlePage = @$_GET['ShowTitlePage'];
	$bShowPageNumber = @$_GET['ShowPageNum'];
	$intPageCount = @$_GET['StartPageNum']-1; // set count to 0
	$bHidePrivateData = @$_GET['HidePrivateData'];
	if(@$_GET['CSVOutput']=="FALSE") {
		$bCSVOutput = FALSE;
	} else {
		$bCSVOutput = TRUE;
	}
	if(@$_GET['XMLOutput']=="FALSE") {
		$bXMLOutput = FALSE;
	} else {
		$bXMLOutput = TRUE;
	}


//	$bXMLOutput = @$_GET['XMLOutput'];
	
	
//	echo "csv ".$bCSVOutput."<p>";
//	echo "xml ".$bXMLOutput;
//exit;

	/*
	echo "<pre>";
	print_r(@$_GET);
	echo "</pre>";
	*/

	$Indv_sql = html_entity_decode(@$_GET['indv_sql']);
	$Indv_sql = urldecode($Indv_sql);

	$Fmly_sql = html_entity_decode(@$_GET['fmly_sql']);
	$Fmly_sql  = urldecode($Fmly_sql);

	if(strlen(trim($Fmly_sql))==0) {
		$Fmly_sql = "TRUE";
	}
	if(strlen(trim($Indv_sql))==0) {
		$Indv_sql = "TRUE";
	}

	if(strpos($Indv_sql, "ChurchDirectoryIndicator")>0 ) {
	} else {
//		$Indv_sql .= " AND ChurchDirectoryIndicator = 'Y' ";
	}
//exit;
	$sql_Fmly = "SELECT Family.FamilyId, Family.FamilyPhoto, Family.FamilyShortName FROM (Individual INNER JOIN Family ON Individual.FamilyId = Family.FamilyId) WHERE $Indv_sql AND $Fmly_sql GROUP BY Family.FamilyId, Family.FamilyPhoto, Family.FamilyShortName ORDER BY Family.FamilyShortName ASC";

//		echo "$sql_Fmly";
//		exit;
//		$sql_Fmly = "SELECT * FROM Family WHERE $Fmly_sql ORDER BY Family.FamilyShortName ;";


	//     echo "<p>$sql<p>";
	$result_Fmly = mysql_query($sql_Fmly);
	$resultsnumber_Fmly = 0;
	$resultsnumber_Fmly = @mysql_num_rows($result_Fmly);

//mysql_num_rows($result_Fmly)
//echo "Num of rows Family  returned : $resultsnumber_Fmly <p>";
//exit;
	//   $links = mysql_fetch_array($result);
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	   
	if(!$bCSVOutput and !$bXMLOutput ) {
	

		$pdf = pdf_new();

		// open a file & save it to specified location
		//pdf_open_file($pdf, "philosophy.pdf");

		if (!pdf_open_file($pdf, "")) {
			print error;
			exit;
		};
		pdf_set_parameter($pdf, "warning", "true");

		pdf_set_info($pdf, "Author", "Uwe Steinmann");
		pdf_set_info($pdf, "Title", "Test for PHP wrapper of PDFlib 2.0");
		pdf_set_info($pdf, "Creator", "See Author");
		pdf_set_info($pdf, "Subject", "Testing");

		// get and use a font object

		$NormalPDFFont_bold  = PDF_findfont($pdf,$BoldFont,"host",0);
		$Helvetica  = PDF_findfont($pdf,$NormalFont,"host",0);
		$NormalPDFFont = $Helvetica  ;

	//	PDF_set_parameter($pdf, "openaction", "fitwidth");
		PDF_set_parameter($pdf, "openaction", "fitpage");
		PDF_set_parameter($pdf, "openmode", "none");
	} // end CSV
	// initialise variables for start
	$y = $intMinBottomPageY-1 ; // set over limit so that new page (page1) will be inserted
	$x = $intTopOfPageX;


	//pdf_setfont($pdf, $NormalPDFFont, 20);
	//pdf_show_xy($pdf, "Number of results : $resultsnumber", $x, $y+15);

	if($resultsnumber_Fmly >0) {
//		echo mysql_num_rows($result_Fmly)."<p>";
		while ($row_Fmly = mysql_fetch_array($result_Fmly)) { 
			$y = $y - 5; // a small separator
			//
			// Grab Family details
			//


		   $FamilyId = $row_Fmly["FamilyId"];
		   $sql_SingleFmly = "SELECT * FROM Family WHERE FamilyId= $FamilyId;";
		   $result_SingleFmly = mysql_query($sql_SingleFmly);						
		   $row_SingleFmly = mysql_fetch_array($result_SingleFmly);
			// count the number of members in family
  		   $sql_Indvcnt = "SELECT COUNT(*) as Fmly_Indvcnt FROM Individual WHERE FamilyId = $FamilyId AND $Indv_sql ;";

			$result_Fmly_Indvcnt = mysql_query($sql_Indvcnt );
			$row_Fmly_Indvcnt = mysql_fetch_array($result_Fmly_Indvcnt);
			$Fmly_Indvcnt = $row_Fmly_Indvcnt["Fmly_Indvcnt"];		

			if($Fmly_Indvcnt>0) {
			   $Indv_FamilyShortName = getFormattedFamilyShortName($FamilyId," ");

				if($row_SingleFmly["ResidentialAddressPrivateIndicator"]=="Y" and $bHidePrivateData) {
					$Fmly_ResAddress = "";
				} else {
					$Fmly_ResAddress  = getFormattedResidentialAddress($FamilyId, chr(10),TRUE,FALSE,FALSE,FALSE ,FALSE , "", $bShowPrivateResidentialAddressesAsXXX, FALSE);
				}
				if($row_SingleFmly["HomePhoneNumberPrivateIndicator"]=="Y" and $bHidePrivateData) {
					$Fmly_HomePhone = "";
				} else {
				   $Fmly_HomePhone     = getFormattedHomePhoneNumber($FamilyId," ",FALSE, TRUE, FALSE, "", $bShowPrivateTelephoneNumbersAsXXX);
				}
			    $Fmly_Photo = $row_Fmly["FamilyPhoto"];
				if(!$bCSVOutput and !$bXMLOutput ) {
		
					/////////////////// Create tmp file //////////////////////////
					if (strlen($Fmly_Photo) > 0){
						$tt = explode( " ", microtime());
						$filename = "".(int)($tt[0] * time()).".jpg";
                        $handle = fopen($filename, 'wb');
						if (!$handle ) {
							 print "Cannot open file ($filename)";
							 exit;
						}

						// Write $somecontent to our opened file.
						$bImage = FALSE;
						$pdf_im_width = 0;
						$pdf_im_height = 0;
						$pdf_im_ratio = 0;
						if(!is_null($Fmly_Photo) and strlen($Fmly_Photo)>0 ) {
							if (!fwrite($handle, $Fmly_Photo)) {
								print "Cannot write to file ($filename)";
								exit;
							}
							else
							{
								$bImage = TRUE;
								if(!$bCSVOutput and !$bXMLOutput ) {
									$pim = pdf_open_image_file($pdf, "jpeg", $filename);
									$pdf_im_width = pdf_get_value($pdf, "imagewidth", $pim);
									$pdf_im_height = pdf_get_value($pdf, "imageheight", $pim);
									// $intImageWidth
									$pdf_im_ratio = (double)$intImageWidth/$pdf_im_width;
								}
							}
						} 
						else 
						{
							$bottom_image_Y = 100000;
						}
					} else
					{
						$bImage = FALSE;
					}
					/////////////////// End Get Image //////////////////////////
			

					$maxFamilySize_Text = $intSmallLineSepSize*2*$Fmly_Indvcnt+50;
					$maxFamilySize_Pic = ((int) @$pdf_im_height * @$pdf_im_ratio)+50;

					$maxFamilySize = max($maxFamilySize_Text, $maxFamilySize_Pic);
					// 
					// Check that the family entry will fit onto the current page
					//

					if (($y-$maxFamilySize)<$intMinBottomPageY){
						// insert new pagge
						// reset top values
						if(!$bCSVOutput) {
							if($intPageCount == (@$_GET['StartPageNum']-1)) 
							{
								// insert titlepage
								if($bShowTitlePage ) {
									if(trim($Indv_sql)=="TRUE") {
										$Indv_sql_ = "n/a";
									}else {
										$pos = strspn($Indv_sql, "TRUE   AND");
										$Indv_sql_ = substr($Indv_sql,$pos);
									}
									if(trim($Fmly_sql)=="TRUE") {
										$Fmly_sql_ = "n/a";
									}else {
			//							$Fmly_sql_ = $Fmly_sql;
										$pos = strspn ($Fmly_sql, "TRUE   AND");
										$Fmly_sql_ = substr($Fmly_sql,$pos);
									}
									if(!$bCSVOutput) {
										printPDFTitlePage($pdf, "Church Directory", "Filtered by : (Indv) ".$Indv_sql_." and (Fmly) ".$Fmly_sql_, $intPageSizeX , $intPageSizeY, $intTopOfPageX, $intTopOfPageY, $intMinBottomPageY, $NormalPDFFont,$NormalPDFFont_bold );
										$intPageCount++;
									}
								}
								// don't end page
							} else
							{
								// Middle footer
								//pdf_setfont($pdf, $NormalPDFFont, 10);
								pdf_show_xy($pdf, "Page $intPageCount", $intPageSizeX/2-10, $intPageCountPosY);
								pdf_end_page($pdf);
							}
							// start a new page (A4)
							pdf_begin_page($pdf, $intPageSizeX , $intPageSizeY );
							$intPageCount++;
		//					pdf_add_outline($pdf, "Page $intPageCount");
							pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
							// reset X,Y values to defaults
							$y = $intTopOfPageY;
							$x = $intTopOfPageX;
							pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
							// insert new top line to page
							PDF_moveto($pdf,$intLineSepLeftX  ,$y+4 );
							PDF_lineto($pdf,$intLineSepRightX ,$y+4 );
							PDF_stroke($pdf);
							$y = $y - $intLineSepSize;
						} //end csv
					}
					else
					{
						// then OK to print
						// $y = $y - $intLineSepSize;
					}
				} // CSV output	

				if(!$bCSVOutput and !$bXMLOutput) {
					pdf_setfont($pdf, $NormalPDFFont_bold, $largeFontSize);
	// SHOW FAMILY NAME
					pdf_add_outline($pdf, "$Indv_FamilyShortName Family");
					pdf_show_xy($pdf, "".strtoupper($Indv_FamilyShortName)."", $x, $y);
				} else {
					if($bCSV_FirstRow) {
						$CSV_FirstRow .= "\nFamilyShortName";
					}
					$CSVOutput_Fmly .= $Indv_FamilyShortName;
					$XMLOutput_Fmly .= $XMLIndent.$XMLIndent."<FamilyShortName>".$Indv_FamilyShortName."</FamilyShortName>\n";

				}
				if(!$bCSVOutput and !$bXMLOutput) {
	// SHOW HOME PHONE
					pdf_show_xy($pdf, "".$Fmly_HomePhone."", $x+$intHomeTelephoneIndentX, $y);
					pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
					$intTopOfAddressY = $y-$HomeAddrHeightY-10;
				} else {
					if($bCSV_FirstRow) {
						$CSV_FirstRow .= ",HomePhoneNumber";
					}
					$XMLOutput_Fmly .= $XMLIndent.$XMLIndent."<FamilyHomePhone>".$Fmly_HomePhone."</FamilyHomePhone>\n";
					$CSVOutput_Fmly .= ",".$Fmly_HomePhone;
				}
	// SHOW HOME ADDRESS
				if(!$bCSVOutput and !$bXMLOutput) {
					$nr = pdf_show_boxed($pdf, $Fmly_ResAddress, $x, $intTopOfAddressY , 160, $HomeAddrHeightY, "left");
				} else {
					
				}
					//
					// now display image
					//
					if (@$bImage == TRUE AND $bShowFamilyPicture ) {
						$bottom_image_Y = $intTopOfAddressY + 10 - ((int) $pdf_im_height * $pdf_im_ratio);
	// SHOW PHOTO
						if(!$bCSVOutput and !$bXMLOutput) {
							pdf_place_image($pdf, $pim, $x, $intTopOfAddressY-50, $pdf_im_ratio );
							pdf_close_image($pdf, $pim);
						}
						@fclose($handle);
						@unlink($filename);
					} else
					{
						$bottom_image_Y = $intTopOfAddressY ;
					}
					// remove of temp files
				

				$sql_Indv = "SELECT * FROM (((Individual) LEFT JOIN Gender ON Individual.GenderCode = Gender.GenderCode) LEFT  JOIN Title ON Individual.Title = Title.Title) LEFT  JOIN RoleType ON Individual.RoleTypeCode = RoleType.RoleTypeCode WHERE Individual.FamilyId=$FamilyId AND  $Indv_sql  ORDER BY Individual.RoleTypeCode DESC, Individual.GenderCode DESC;";
				$result_Indv = mysql_query($sql_Indv);
				// insert a seperator row
				$y = $y - $intSmallLineSepSize;

				while ($row_Indv = mysql_fetch_array($result_Indv)) { 
					//
					// Print Individual
					//

					$Indv_id = $row_Indv["IndividualId"];
					$Indv_FirstName = $row_Indv["FirstName"];
					$Indv_Surname = $row_Indv["Surname"];
					$Indv_IndividualPhoto = $row_Indv["IndividualPhoto"];

					$Indv_ModificationTMS = @$row_Indv["ModificationTMS"];
					$Indv_ModificationUserId = @$row_Indv["ModificationUserId"];
					$Indv_CreationTMS = @$row_Indv["CreationTMS"];
					$Indv_CreationUserId = @$row_Indv["CreationUserId"];
					
					if($bShowRole) {
						$Indv_role= $row_Indv["RoleTypeCode"];
					} else {
						$Indv_role= "";
					}
					if($bShowGender) {
						$Indv_Gender = getLookValue("Gender", "GenderCode", $row_Indv["GenderCode"], "Description");
					} else {
						$Indv_Gender = "";
					}
					if(($bHidePrivateData and $row_Indv["MobilePhonePrivateIndicator"]=="Y") OR $bShowMobilePhoneNumber==FALSE) {
						$Indv_MobilePhoneNum = "";
					} else {
						$Indv_MobilePhoneNum = getFormattedMobilePhoneNumber($row_Indv["IndividualId"]," ", FALSE, FALSE ,"", $bShowPrivateTelephoneNumbersAsXXX);
					}
					if(($bHidePrivateData and $row_Indv["WorkPhonePrivateIndicator"]=="Y") OR $bShowWorkPhoneNumber==FALSE) {
						$Indv_WorkPhoneNum = "";
					} else {
						$Indv_WorkPhoneNum = getFormattedWorkPhoneNumber($row_Indv["IndividualId"]," ",FALSE,TRUE,FALSE ,"", $bShowPrivateTelephoneNumbersAsXXX); 
					}
					if(($bHidePrivateData and $row_Indv["HomeEmailAddressPrivateIndicator"]=="Y") OR $bShowHomeEmailAddress==FALSE) {
						$Indv_HomeEmail = "";
					} else {
						$Indv_HomeEmail = getEmailAddress($Indv_id ,"HOME",FALSE,"",$bShowPrivateEmailAddressesAsXXX);
					}
					if(($bHidePrivateData and $row_Indv["WorkEmailAddressPrivateIndicator"]=="Y") OR $bShowWorkEmailAddress==FALSE) {
						$Indv_WorkEmail = "";
					} else {
						$Indv_WorkEmail = getEmailAddress($Indv_id ,"WORK",FALSE,"",$bShowPrivateEmailAddressesAsXXX);
					}
					if($bShowSchoolGrade) {
						$Indv_SchoolGrade = getSchoolGrade($row_Indv["KindergartenCommenceYear"]);
					} else {
						$Indv_SchoolGrade = "";
					}
					if(!$bCSVOutput and !$bXMLOutput) {
						pdf_setfont($pdf, $NormalPDFFont, $mediumFontSize);
	// SHOW FIRSTNAME						
						pdf_show_xy($pdf, "$Indv_FirstName", $x+$intFirstNameIndentX, $y);
					} else {
						if($bCSV_FirstRow) {
							$CSV_FirstRow .= ",FirstName";
						}
						$CSVOutput_Indv .= ",".$Indv_FirstName;
						$XMLOutput_Indv .= $XMLIndent.$XMLIndent.$XMLIndent."<FirstName>".$Indv_FirstName."</FirstName>\n";
					}						
					$tmpstr ="";
					if($bShowGender) {
						$tmpstr = "$Indv_Gender ";
					}
					if($bShowRole) {
						$tmpstr = trim($tmpstr)." $Indv_role ";
					}
					$tmpstr = trim($tmpstr);
					if(!$bCSVOutput and !$bXMLOutput) {
	// SHOW ROLE						
						pdf_setfont($pdf, $NormalPDFFont_bold, $tinyFontSize);
						if($Indv_role == "Child" and strlen($Indv_SchoolGrade)>0) {
							$tmpstr = "(".trim($tmpstr)." in $Indv_SchoolGrade)";
							pdf_show_xy($pdf, $tmpstr, $x+$intIndvRoleIndentX, $y);
						}else
						{
							if(strlen($tmpstr)>0) {
								pdf_show_xy($pdf, "(".trim("$tmpstr").")", $x+$intIndvRoleIndentX, $y);
							}
						}
					} else {
						if($bCSV_FirstRow) {
							$CSV_FirstRow .= ",Role";
						}
						$CSVOutput_Indv .= ",".$tmpstr;
						$XMLOutput_Indv .= $XMLIndent.$XMLIndent.$XMLIndent."<Role>".$tmpstr."</Role>\n";
					}
					if(!$bCSVOutput and !$bXMLOutput) {
						pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
					}
						$y_tmp = $y;
						$y_tmp2 = $y;
						if(!is_null($Indv_WorkPhoneNum) and strlen($Indv_WorkPhoneNum)>0) {
							$y_tmp = $y_tmp - $intSmallLineSepSize;
// SHOW WORK PHONE
							if(!$bCSVOutput and !$bXMLOutput and $bShowWorkPhoneNumber) {
								pdf_setfont($pdf, $NormalPDFFont, $tinyFontSize);
								pdf_show_xy($pdf, "Work: $Indv_WorkPhoneNum", $x+$intFirstDetailsX , $y_tmp);
							} 
						}
						if(($bCSVOutput or $bXMLOutput) and $bShowWorkPhoneNumber) {
							if($bCSV_FirstRow) {
								$CSV_FirstRow .= ",WorkPhoneNum";
							}
							$CSVOutput_Indv .= ",".$Indv_WorkPhoneNum;
							$XMLOutput_Indv .= $XMLIndent.$XMLIndent.$XMLIndent."<WorkPhoneNum>".$Indv_WorkPhoneNum."</WorkPhoneNum>\n";
						}

						if(!is_null($Indv_MobilePhoneNum) and strlen($Indv_MobilePhoneNum)>0) {
							$y_tmp = $y_tmp - $intSmallLineSepSize;
							if(!$bCSVOutput and !$bXMLOutput and $bShowMobilePhoneNumber) {
								pdf_setfont($pdf, $NormalPDFFont, $tinyFontSize);
	// SHOW MOBILE PHONE
								pdf_show_xy($pdf, "Mobile: $Indv_MobilePhoneNum", $x+$intFirstDetailsX , $y_tmp);
							} 
						}
						if($bShowMobilePhoneNumber AND ($bCSVOutput or $bXMLOutput)) {
							if($bCSV_FirstRow) {
								$CSV_FirstRow .= ",MobilePhoneNum";
							}
							$CSVOutput_Indv .= ",".$Indv_MobilePhoneNum;
							$XMLOutput_Indv .= $XMLIndent.$XMLIndent.$XMLIndent."<MobilePhoneNum>".$Indv_MobilePhoneNum."</MobilePhoneNum>\n";
						}

						
						if(!is_null($Indv_WorkEmail) and strlen($Indv_WorkEmail)>0) {
							$y_tmp2 = $y_tmp2 - $intSmallLineSepSize;
							if(!$bCSVOutput and !$bXMLOutput and $bShowWorkEmailAddress) {
								pdf_setfont($pdf, $NormalPDFFont, $tinyFontSize);
	// SHOW WORK EMAIL
								pdf_show_xy($pdf, "$Indv_WorkEmail" , $x+$intLeftEmailDetailsIndentX , $y_tmp2);
							} 
						}
						if (($bCSVOutput or $bXMLOutput) and $bShowWorkEmailAddress){
								if($bCSV_FirstRow) {
									$CSV_FirstRow .= ",WorkEmail";
								}
								$CSVOutput_Indv .= ",".$Indv_WorkEmail;
								$XMLOutput_Indv .= $XMLIndent.$XMLIndent.$XMLIndent."<WorkEmail>".$Indv_WorkEmail."</WorkEmail>\n";
							}
						if(!is_null($Indv_HomeEmail) and strlen($Indv_HomeEmail)>0) {
							$y_tmp2 = $y_tmp2 - $intSmallLineSepSize;
							if(!$bCSVOutput and !$bXMLOutput and $bShowHomeEmailAddress) {
								pdf_setfont($pdf, $NormalPDFFont, $tinyFontSize);
	// SHOW HOME EMAIL
								pdf_show_xy($pdf, "$Indv_HomeEmail" , $x+$intLeftEmailDetailsIndentX , $y_tmp2);
							} 
						}
						if (($bCSVOutput or $bXMLOutput) and $bShowHomeEmailAddress) {
							if($bCSV_FirstRow) {
								$CSV_FirstRow .= ",HomeEmail";
							}
							$CSVOutput_Indv .= ",".$Indv_HomeEmail;
							$XMLOutput_Indv .= $XMLIndent.$XMLIndent.$XMLIndent."<HomeEmail>".$Indv_HomeEmail."</HomeEmail>\n";
						}
						$y = $y_tmp2;
						if($y > $y_tmp) {
							$y = $y_tmp;				
						}
						if(!$bCSVOutput and !$bXMLOutput) {
							pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
					//			pdf_show_xy($pdf, "..", $x-10, $y);	
							// insert a seperator row
							$y = $y - $intLineSepSize;
						} //end $bcsvoutput
					else {
						// CSV output	
						if($bCSV_FirstRow) {
							$CSV_FirstRow .= ",SchoolGrade";
							$CSV_FirstRow .= ",Gender";
							$CSV_FirstRow .= ",Indv_ModificationTMS";
							$CSV_FirstRow .= ",Indv_ModificationUserId";
							$CSV_FirstRow .= ",Indv_CreationTMS";
							$CSV_FirstRow .= ",Indv_CreationUserId";
						}
						$CSVOutput_Indv .= ",".$Indv_SchoolGrade;
						$CSVOutput_Indv .= ",".$Indv_Gender;
						$CSVOutput_Indv .= ",".$Indv_ModificationTMS;
						$CSVOutput_Indv .= ",".$Indv_ModificationUserId;
						$CSVOutput_Indv .= ",".$Indv_CreationTMS;
						$CSVOutput_Indv .= ",".$Indv_CreationUserId;
						$CSVOutput .= $CSVOutput_Fmly.$CSVOutput_Indv."\n";
						$CSVOutput_Indv = "";

						$XMLOutput_Indv .= $XMLIndent.$XMLIndent.$XMLIndent."<SchoolGrade>".$Indv_SchoolGrade."</SchoolGrade>\n";
						$XMLOutput_Indv .= $XMLIndent.$XMLIndent.$XMLIndent."<Gender>".$Indv_Gender."</Gender>\n";
						$XMLOutput_Indv .= $XMLIndent.$XMLIndent.$XMLIndent."<ModificationTMS>".$Indv_ModificationTMS."</ModificationTMS>\n";
						$XMLOutput_Indv .= $XMLIndent.$XMLIndent.$XMLIndent."<ModificationUserId>".$Indv_ModificationUserId."</ModificationUserId>\n";
						$XMLOutput_Indv .= $XMLIndent.$XMLIndent.$XMLIndent."<CreationTMS>".$Indv_CreationTMS."</CreationTMS>\n";
						$XMLOutput_Indv .= $XMLIndent.$XMLIndent.$XMLIndent."<CreationUserId>".$Indv_CreationUserId."</CreationUserId>\n";

						$XMLOutput_IndvFamily .= $XMLIndent.$XMLIndent."<Indv>\n".$XMLOutput_Indv.$XMLIndent.$XMLIndent."</Indv>\n";
						$XMLOutput_Indv = "";

						$bCSV_FirstRow = FALSE;
					
					}
				} // end While Indv 
				$y = $y - $intLineSepSize;

				if($y > $bottom_image_Y ) {
//pdf_show_xy($pdf, $bottom_image_Y."bi" , 10 , $y+80);
					$y = $bottom_image_Y - $intMinSepAfterAddrY;
					$bottom_image_Y = $y;
				} else {
					if ( $y > ($intTopOfAddressY ) )
					{
							$y = $intTopOfAddressY;//- $intMinSepAfterAddrY;
					} else {
						$y = $y + 20;
					}
					
				}
//pdf_show_xy($pdf, $intTopOfAddressY."ta" , 10 , $y+50);

//pdf_show_xy($pdf, $y."a" , 10 , $y);
//pdf_show_xy($pdf, $y."b" , 10 , $y);
				//
				// Insert line at end of Family
				//

				if(!$bCSVOutput and !$bXMLOutput) {
					PDF_moveto($pdf,$intLineSepLeftX  ,$y );
					PDF_lineto($pdf,$intLineSepRightX ,$y );
					PDF_stroke($pdf);
				}
				$y = $y - $intLineSepSize;
				$XMLOutput .= $XMLIndent."<Family>\n".$XMLOutput_Fmly.$XMLOutput_IndvFamily.$XMLIndent."</Family>\n";
				$XMLOutput_IndvFamily = "";
				$XMLOutput_Fmly = "";
				$CSVOutput_Fmly = "";
				$CSVOutput_Indv = "";
			} // end if count family
		} // end while family
	} // end if rowcount

	if(	$intPageCount == (@$_GET['StartPageNum']-1)){
		// family row count is zero
		// insert titlepage
		if($bShowTitlePage ) {
			if(trim($Indv_sql)=="TRUE") {
				$Indv_sql_ = "n/a";
			}else {
				$pos = strspn($Indv_sql, "TRUE   AND");
				$Indv_sql_ = substr($Indv_sql,$pos);
			}
			if(trim($Fmly_sql)=="TRUE") {
				$Fmly_sql_ = "n/a";
			}else {
				$pos = strspn ($Fmly_sql, "TRUE   AND");
				$Fmly_sql_ = substr($Fmly_sql,$pos);
			}
			if(!$bCSVOutput and !$bXMLOutput) {
				printPDFTitlePage($pdf, "Church Directory", "Filtered by : (Indv) ".$Indv_sql_." and (Fmly) ".$Fmly_sql_, $intPageSizeX , $intPageSizeY, $intTopOfPageX, $intTopOfPageY, $intMinBottomPageY, $NormalPDFFont,$NormalPDFFont_bold );
			}
			$intPageCount++;
		} // end show titlepage
		if(!$bCSVOutput and !$bXMLOutput) {
			pdf_begin_page($pdf, $intPageSizeX , $intPageSizeY );
			$intPageCount++;
			pdf_add_outline($pdf, "Page $intPageCount");
			pdf_setfont($pdf, $NormalPDFFont, $hugeFontSize);
			pdf_show_xy($pdf, "Query returned no data!", $intPageSizeX/2-220 , $intTopOfPageY-100);
			pdf_setfont($pdf, $NormalPDFFont, $largeFontSize);
			$nr = pdf_show_boxed($pdf, print_r($_GET,TRUE) , $intPageSizeX/2-220, $intTopOfPageY-300, 210, 180, "left");
		}
	} // end if	
	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	if(!$bCSVOutput and !$bXMLOutput) {

		// Middle footer
		pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
		pdf_show_xy($pdf, "Page $intPageCount", $intPageSizeX/2-10, $intPageCountPosY);
		pdf_end_page($pdf);
		pdf_close($pdf);

		$buf = pdf_get_buffer($pdf);
		$len = strlen($buf);

		header("Content-type: application/pdf");
		header("Content-Length: $len");
		header("Content-Disposition: inline; filename=foo.pdf");
		print $buf;

		pdf_delete($pdf);
	} else {
		$XMLOutputHeader = $XMLIndent."<ReportType>".$HTTP_SERVER_VARS['PHP_SELF']."</ReportType>\n";
		$XMLOutputHeader .= $XMLIndent."<ReportDate>".date("g:i a j F Y")."</ReportDate>\n";
		$XMLOutputHeader .= $XMLIndent."<ReportProducedBy>".$_SESSION['username']."</ReportProducedBy>\n";
		$XMLOutputHeader .= $XMLIndent."<ReportFilter>\n";
		$XMLOutputHeader .= $XMLIndent.$XMLIndent."<Indv>".trim($Indv_sql)."</Indv>\n";
		$XMLOutputHeader .= $XMLIndent.$XMLIndent."<Fmly>".trim($Fmly_sql)."</Fmly>\n";
		$XMLOutputHeader .= $XMLIndent."</ReportFilter>\n";
		$CSVOutput = $CSV_FirstRow."\n".$CSVOutput;
		$XMLOutput = "<PACTS>\n".$XMLOutputHeader."\n".$XMLOutput."\n</PACTS>";
if($bCSVOutput) {
//	echo "csv";
//	exit;
		header("Content-type: text/csv");
		header("Content-Length: ".strlen($CSVOutput));
		header("Content-Disposition: attachment; filename=report.csv");
//		print $buf;
	echo $CSVOutput;
	exit;
}
if($bXMLOutput) {
//	echo "xml";
//	exit;
		header("Content-type: text/xml");
		header("Content-Length: ".strlen($XMLOutput));
		header("Content-Disposition: attachment; filename=report.xml");
	echo $XMLOutput;
//	echo "XML : <p>".htmlspecialchars($XMLOutput);
	exit;
}
//		echo "<pre>";
//		echo "</pre><p>";
//		echo "<pre>";
//		echo "</pre><p>";
	}
?>

